package cn.peng.stu4teach.pages.todo;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;

import java.util.ArrayList;
import java.util.List;

import cn.peng.stu4teach.BR;
import cn.peng.stu4teach.R;
import cn.peng.stu4teach.databinding.ItemTodoBinding;
import cn.peng.stu4teach.pages.todo.bean.TodoItem;
import cn.peng.stu4teach.util.webview.WebViewActivity;

/**
 * 待办的适配器
 */
public class ToDoAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private List<TodoItem> items = new ArrayList<TodoItem>();

    public void setItems (List<TodoItem> pItems) {
        items = pItems;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder (@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        ItemTodoBinding binding = DataBindingUtil.inflate(inflater, R.layout.item_todo, parent, false);
        return new TodoVh(binding);
    }

    @Override
    public void onBindViewHolder (@NonNull RecyclerView.ViewHolder holder, int position) {
        if (!(holder instanceof TodoVh)) {
            return;
        }

        ItemTodoBinding binding = ((TodoVh) holder).binding;
        TodoItem item = items.get(position);
        // 绑定变量方式1
        binding.setItem(item);
        // 绑定变量方式2
        binding.setVariable(BR.listener, new View.OnClickListener() {
            @Override
            public void onClick (View v) {
                WebViewActivity.start(v.getContext(), item.title, item.link);
            }
        });
    }

    @Override
    public int getItemCount () {
        LogUtils.d("TodoAdapter",items.size());
        return items.size();
    }

    static class TodoVh extends RecyclerView.ViewHolder {
        ItemTodoBinding binding;

        public TodoVh (@NonNull ItemTodoBinding pBinding) {
            super(pBinding.getRoot());
            binding = pBinding;
        }
    }
}
